package com.two.screen.water.balance.image

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.widget.ImageView
import androidx.annotation.Nullable
import cc.shinichi.library.glide.FileTarget
import cc.shinichi.library.tool.image.ImageUtil
import cc.shinichi.library.view.helper.ImageSource
import cc.shinichi.library.view.helper.SubsamplingScaleImageViewDragClose
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.FitCenter
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.two.screen.water.balance.R
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.utils.CommUtils
import com.two.screen.water.balance.utils.ToastUtil
import com.two.screen.water.balance.utils.Urls
import java.io.File

/**
 * 创建者     Noel
 * 创建时间   2017/5/9 10:48
 * 描述	     图片管理
 */
object ImageManger {
    fun setCenterCropImg(
        context: Context, url: String?, iv: ImageView, duration: Int = 300,
        errorResInt: Int = 0, placeResInt: Int = 0
    ) {
        iv.setImageResource(errorResInt)
        if (url == null || url.isEmpty()) {
            iv.scaleType = ImageView.ScaleType.CENTER_CROP
        } else {
            var options = RequestOptions().priority(Priority.HIGH) //优先级
                //.error(errorResInt) //加载失败显示图片
                //.placeholder(placeResInt)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .transform(MultiTransformation(CenterCrop()/*, GlideRoundTransform(raid)*/))
            Glide.with(context)
                .load(formatUrl(url))
                .apply(options)
                .transition(DrawableTransitionOptions.withCrossFade(duration))
                .into(iv)
        }
    }


    fun setBgImageCenterCrop(context: Context, url: String?, iv: ImageView) {
        var options = RequestOptions().priority(Priority.HIGH) //优先级
            .error(R.drawable.empty_food_default1) //加载失败显示图片
            //.placeholder(R.drawable.ic_empty_food_white)
            .transform(MultiTransformation(CenterCrop()/*, GlideRoundTransform(raid)*/))
        CommUtils.println("ImageManger:", "setBgImage::$url")
        Glide.with(context)
            .load(formatUrl(url))
            .apply(options)
            .into(iv)
    }

    fun setBgImageFitCenter(context: Context, url: String?, iv: ImageView) {
        var options = RequestOptions().priority(Priority.HIGH) //优先级
            .error(R.drawable.empty_food_default1) //加载失败显示图片
            //.placeholder(R.drawable.ic_empty_food_white)
            .transform(MultiTransformation(FitCenter()/*, GlideRoundTransform(raid)*/))
        CommUtils.println("ImageManger:", "setBgImage::$url")
        Glide.with(context)
            .load(formatUrl(url))
            .apply(options)
            .into(iv)
    }

    fun setCenterCropImg(context: Context, url: String?, iv: SubsamplingScaleImageViewDragClose) {
        iv.apply {
            Glide.with(context)
                .downloadOnly()
                .load(formatUrl(url))
                //.error(errorResInt) //加载失败显示图片
                //.placeholder(placeResInt)
                //.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .addListener(object : RequestListener<File> {
                    override fun onLoadFailed(@Nullable e: GlideException?, model: Any, target: Target<File>, isFirstResource: Boolean): Boolean {
                        //iv.setImageResource()
                        //iv.setImage(ImageSource.resource(R.drawable.status_error_icon))
                        ToastUtil.showToast("加载失败：$e")
                        //mLoadingDialog.dismiss()
                        return true
                    }

                    override fun onResourceReady(
                        resource: File,
                        model: Any,
                        target: Target<File>,
                        dataSource: DataSource,
                        isFirstResource: Boolean
                    ): Boolean {
                        //TODO:
                        val imagePath = resource.absolutePath
                        this@apply.orientation = SubsamplingScaleImageViewDragClose.ORIENTATION_USE_EXIF
                        val imageSource = ImageSource.uri(Uri.fromFile(File(imagePath)))
                        if (ImageUtil.isBmpImageWithMime(imagePath)) {
                            imageSource.tilingDisabled()
                        }
                        this@apply.setImage(imageSource)

                        return true
                    }
                }).into(object : FileTarget() {
                    override fun onLoadStarted(@Nullable placeholder: Drawable?) {
                        //photoView.setImage(ImageSource.resource(R.drawable.status_error_icon))
                    }
                })
        }
    }


    fun setFitCenterImg1(context: Context, url: String?, iv: ImageView, duration: Int = 300, errorResInt: Int = 0, placeResInt: Int = 0) {
        var options = RequestOptions().priority(Priority.HIGH) //优先级
            .error(errorResInt) //加载失败显示图片
            .placeholder(placeResInt)
            .transform(MultiTransformation(FitCenter()/*, GlideRoundTransform(raid)*/))
        CommUtils.println("ImageManger:", url ?: "没有？")
        Glide.with(context)
            .load(formatUrl(url))
            //.transition(DrawableTransitionOptions.withCrossFade(duration))
            .apply(options)
            .into(iv)
    }

    fun setFitCenterImg(context: Context, url: String?, iv: ImageView, duration: Int = 300, errorResInt: Int = 0, placeResInt: Int = 0) {
        var options = RequestOptions()
            .priority(Priority.HIGH) //优先级
            .error(errorResInt) //加载失败显示图片
            .placeholder(placeResInt)
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
            .transform(MultiTransformation(FitCenter()/*, GlideRoundTransform(raid)*/))
        // if (w != 0 && h != 0) options.override(w, h)
        //if (w != 0 && h != 0) options.override(Int.MIN_VALUE, Int.MIN_VALUE)
        //CommUtils.println("ImageManger:", /*Urls.BaseImgUrl + */url)
        Glide.with(context)
            .load(formatUrl(url))
            .apply(options)
            .transition(DrawableTransitionOptions.withCrossFade(duration))
            .into(iv)
    }

    //显示圆角图
    fun setCircleImg(context: Context, url: String?, iv: ImageView, duration: Int = 300, errorResInt: Int = 0, placeResInt: Int = 0) {
        var options = RequestOptions()
            .priority(Priority.HIGH) //优先级
            .error(errorResInt) //加载失败显示图片
            .placeholder(placeResInt)
            .diskCacheStrategy(DiskCacheStrategy.ALL)

        Glide.with(context)
            .load(formatUrl(url))
            .apply(RequestOptions.bitmapTransform(CircleCrop()))
            .apply(options)
            .transition(DrawableTransitionOptions.withCrossFade(duration))
            .into(iv)
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    fun getBitmap(context: Context, vectorDrawableId: Int): Bitmap? {
        var bitmap: Bitmap? = null
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            val vectorDrawable = context.getDrawable(vectorDrawableId)
            bitmap = Bitmap.createBitmap(
                vectorDrawable!!.intrinsicWidth,
                vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(bitmap)
            vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
            vectorDrawable.draw(canvas)
        } else {
            bitmap = BitmapFactory.decodeResource(context.resources, vectorDrawableId)
        }
        return bitmap
    }

    /*设置白色 logo*/
    fun setLogWhite(context: Context, iv: ImageView, url: String? = Urls.LOGO_URL_WHITE) {
        var options = RequestOptions().priority(Priority.HIGH) //优先级
            .transform(MultiTransformation(FitCenter()))
        Glide.with(context)
            .load(formatUrl(url))
            .apply(options)
            .into(iv)
    }

    /*设置app logo*/
    fun setLogoApp(context: Context, iv: ImageView, url: String? = Urls.LOGO_URL_APP) {
        var options = RequestOptions().priority(Priority.HIGH) //优先级
            .transform(MultiTransformation(FitCenter()))
        Glide.with(context)
            .load(formatUrl(url))
            .apply(options)
            .into(iv)
    }

    /*设置蓝色 logo*/
    fun setLogoBlue(context: Context, iv: ImageView, url: String? = Urls.LOGO_URL_BLUE) {
        var options = RequestOptions().priority(Priority.HIGH) //优先级
            .transform(MultiTransformation(FitCenter()))
        Glide.with(context)
            .load(formatUrl(url))
            .apply(options)
            .into(iv)
    }


    private fun formatUrl(url: String?): String? {
        var newUrl = if (url?.contains("http://") != false || url.contains("https://")) url else DataApi.mImageUrl + url
        CommUtils.println("formatUrl->", "newUrl:$newUrl")
        //if (newUrl?.contains(".jpg") != false) newUrl else newUrl.plus(".jpg")
        return newUrl
    }
}
